<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>顶部通栏</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      body {
        width: 100%;
        height: 2000px;
      }

      #banner {
        width: 100%;
        height: 0;
        transition: height 0.5s linear;
        position: fixed;
        top: 0;
        left: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        overflow: hidden;
        background-color: skyblue;
        color: white;
        font-size: 30px;
      }

      #btnBack {
        width: 150px;
        height: 50px;
        background-color: skyblue;
        color: white;

        display: flex;
        justify-content: center;
        align-items: center;

        position: fixed;
        right: 20px;
        bottom: 20px;
      }
    </style>
  </head>

  <body>
    <div id="banner">我是顶部通栏</div>
    <button id="btnBack">返回顶部</button>

    <script>
      // 监听滚动事件
      window.onscroll = function () {
        // scrollTop一旦超过500 则通栏与回顶部按钮一起出现
        if (document.documentElement.scrollTop >= 500) {
          banner.style.height = "80px";
          btnBack.style.display = "flex";
        }
        // 否则一起消失
        else {
          banner.style.height = "0px";
          btnBack.style.display = "none";
        }
      };

      var timerId = null;
      btnBack.onclick = function () {
        //   事件节流
        if (timerId) {
          // 动画正在跑 不响应用户的点击事件
          console.log("代码不理我");
          return;
        }

        // 创建定时器 每秒25帧 每40毫秒回调一次
        timerId = setInterval(function () {
          // 每帧将scrollTop减少一点点
          document.documentElement.scrollTop -= 5;

          // 一旦scrollTop为零 清除定时器
          if (document.documentElement.scrollTop <= 0) {
            clearInterval(timerId);
            timerId = null;
            console.log("定时器已清除");
          }
        }, 40);
      };
    </script>
  </body>
</html>
